package com.itcam.elasticsearch.once;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.indices.CreateIndexRequest;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;

import java.io.IOException;

public class CreateElasticsearchIndex {
    public static void main(String[] args) {
        // 创建一个低级别 REST 客户端，连接到本地运行在 9200 端口的 Elasticsearch 实例
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200)).build();
        // 创建 Elasticsearch 传输层，使用 Jackson 作为 JSON 映射器，用于处理数据的序列化和反序列化
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        // 创建 Elasticsearch 客户端，用于与 Elasticsearch 进行交互
        ElasticsearchClient client = new ElasticsearchClient(transport);

        try {
            // 定义要创建的索引名称
            String indexName = "your_new_index";
            // 创建创建索引的请求
            CreateIndexRequest request = new CreateIndexRequest.Builder()
                   .index(indexName)
                   .build();
            // 执行创建索引的请求
            CreateIndexResponse response = client.indices().create(request);

            if (response.acknowledged()) {
                System.out.println("索引 " + indexName + " 创建成功");
            } else {
                System.out.println("索引 " + indexName + " 创建失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭传输层
                transport.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
